<template>
  <div class="login">
    <!-- 头部 -->
    <van-nav-bar title="会员登录" left-arrow @click-left="onClickLeft" />
    <!-- 主体 -->
    <div class="body">
      <p>手机号登录</p>
      <span>未注册的手机号登录后将自动注册</span>
    </div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="phoneNumber"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <div class="graph-info">
        <van-field
          v-model="graphCode"
          type="text"
          name="图形验证码"
          label="图形验证码"
          placeholder="请输入图形验证码"
          :rules="[{ required: true, message: '请填写图形验证码' }]"
          class="graph-input"
        />
        <img v-if="graphCodeUrl" :src="graphCodeUrl" @click="getGraphCodeImg" />
      </div>
      <div class="sms-info">
        <van-field
          v-model="smsCode"
          class="sms-input"
          type="text"
          name="短信验证码"
          label="短信验证码"
          placeholder="请输入短信验证码"
          :rules="[{ required: true, message: '请填写短信验证码' }]"
        /><span @click="getSmsCode">{{
          remainTime == totalSecond
            ? "获取短信验证码"
            : remainTime + "后重新发送"
        }}</span>
      </div>
      <div style="margin: 50px 16px">
        <van-button
          round
          block
          color="rgb(250, 170, 43)"
          type="info"
          native-type="submit"

          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// login.js中按需导出，这里按需导入
import { getGraphCodeImg, getSmsCode, login } from '@/api/login'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'LoginIndex',
  data () {
    return {
      phoneNumber: '',
      // 验证码
      graphCode: '',
      // 图形验证码唯一标识
      graphKey: '',
      smsCode: '',
      // 图片地址
      graphCodeUrl: '',
      remainTimeIsShow: false,
      remainTime: 60,
      totalSecond: 60, // 总秒数
      timer: null
    }
  },
  computed: {
    ...mapGetters('login', ['getUserInfo'])
  },
  methods: {
    ...mapMutations('login', ['setUserInfo']),
    async onSubmit () {
      const res = await login(this.phoneNumber, this.smsCode)
      // 使用响应拦截器处理报错（见request.js），await只会等待成功的响应
      console.log(res)
      this.setUserInfo({
        token: res.data.token,
        userId: res.data.userId
      })
      // 判断如果有回跳参数即backUrl  即从其他页面跳过来的
      // console.log(this.getUserInfo)
      const url = this.$route.query.backUrl || '/'
      this.$router.replace(url)
    },
    onClickLeft () {
      this.$router.go(-1)
    },
    validFn () {
      // 手机号正则表达式
      if (!/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
        this.$toast.fail('手机号不合法')
        return false
      }

      // 验证码正则表达式
      if (!/^\w{4}$/.test(this.graphCode)) {
        this.$toast.fail('验证码不合法')
        return false
      }
      return true
    },
    validSmsCode () {
      return /^[0-9]{6}$/.test(this.smsCode)
    },
    async getSmsCode () {
      if (!this.validFn()) {
        return
      }
      // 发送请求，请求成功之后
      await getSmsCode(this.graphCode, this.graphKey, this.phoneNumber)

      // 使用响应拦截器处理response，就不用判断 status了

      // 当目前没有定时器开着，且remainTime和totalSecond一致才可以倒计时
      if (!this.timer && this.remainTime === this.totalSecond) {
        // 开启定时器
        this.timer = setInterval(() => {
          console.log('定时器执行中')

          this.remainTime--
          if (this.remainTime <= 0) {
            clearInterval(this.timer)
            this.timer = null // 重置定时器id
            this.remainTime = this.totalSecond
          }
        }, 1000)
      }
    },
    async getGraphCodeImg () {
      const {
        data: { base64, key }
      } = await getGraphCodeImg()
      this.graphCodeUrl = base64
      this.graphKey = key
    }
  },

  created () {
    this.getGraphCodeImg()
  },
  destroyed () {
    // 在页面销毁的时候清除定时器,不销毁的话影响性能
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
.login {
  .body {
    margin: 50px 0px 20px 15px;
    p {
      font-size: 20px;
      margin-bottom: 10px;
    }
    span {
      color: rgb(216, 216, 216);
    }
  }
  .van-form {
    .graph-info {
      .graph-input {
        width: 65%;
        float: left;
      }
      img {
        height: 35px;
        margin-top: 5px;
        margin-right: 16px;
        float: right;
      }
    }
    .sms-info {
      .sms-input {
        width: 65%;
        float: left;
      }
      span {
        float: right;
        line-height: 35px;
        margin-right: 16px;
        color: rgb(250, 170, 43);
      }
    }
  }
}
</style>
